package zut.wework.api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zut.wework.entity.WxDept;
import zut.wework.entity.ZsjBzks;
import zut.wework.mapper.WxDeptMapper;
import zut.wework.utils.HttpClientUtil;
import zut.wework.utils.JsonUtil;
import zut.wework.utils.RedisUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.TimeUnit;

/**
 * @author: Mr.Liu
 * @create: 2022-04-23 18:04
 */
@Slf4j
@Component
public class WxApi {

    //AccessToken存Redis的key
    public static final String TOKEN_REDIS = "access_token";

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private WxDeptMapper wxDeptMapper;


    /**
     * 获取AccessToken
     *
     * @return AccessToken
     */
    public String getAccessToken(String secret) {
        String at = (String) redisUtil.get(TOKEN_REDIS);
        if (at != null) {
            return at;
        }
        int i = 0;
        while (i < 3) {
            String res = HttpClientUtil.get(String.format(WorkWXAPI.GET_ACCESS_TOKEN_URL, WorkWXAPI.CORPID, secret));
            Map<String, Object> mapData = null;
            mapData = JsonUtil.toMap(res);
            at = (String) mapData.get("access_token");
            Integer errcode = (Integer) mapData.get("errcode");
            if (at != null && errcode == 0) {
                log.info("获取AccessToken成功:{}", at);
                redisUtil.set(TOKEN_REDIS, at, 90L, TimeUnit.SECONDS);
                return at;
            }
            log.info("第{}次获取AccessToken失败", i + 1);
            i++;
        }
        log.error("获取AccessToken失败！！！");
        return null;
    }

    //test 可以删除
    public String getKeBiaoAccessToken() {
        String at = (String) redisUtil.get(TOKEN_REDIS);
        if (at != null) {
            return at;
        }
        int i = 0;
        while (i < 3) {
            String res = HttpClientUtil.get(String.format(WorkWXAPI.GET_ACCESS_TOKEN_URL, WorkWXAPI.CORPID, "GFgLb4ziLeAhfCzBvcHm_5ZQybuJa0IWuoHxX4YszhA"));
            Map<String, Object> mapData = null;
            mapData = JsonUtil.toMap(res);
            at = (String) mapData.get("access_token");
            Integer errcode = (Integer) mapData.get("errcode");
            if (at != null && errcode == 0) {
                log.info("获取AccessToken成功:{}", at);
                redisUtil.set(TOKEN_REDIS, at, 90L, TimeUnit.SECONDS);
                return at;
            }
            log.info("第{}次获取AccessToken失败", i + 1);
            i++;
        }
        log.error("获取AccessToken失败！！！");
        return null;
    }


    /**
     * 新建部门
     *
     * @param wxDept
     * @return
     */
    public boolean creatDept(WxDept wxDept) {
        String accessToken = getAccessToken(WorkWXAPI.ADDRESS_BOOK_SECRET);
        if (accessToken == null) {
            log.error("创建部门：获取Token失败！");
            return false;
        }
        Map<String, Object> deptMap = new HashMap<>();
        deptMap.put("name", wxDept.getName());
        deptMap.put("parentid", wxDept.getParentid());
        if (wxDept.getPx() != null) {
            deptMap.put("order", wxDept.getPx());
        }
        deptMap = JsonUtil.toMap(HttpClientUtil.post(String.format(WorkWXAPI.DEPARTMENT_CREATE, accessToken), JsonUtil.toJson(deptMap)));
        int errcode = (int) deptMap.get("errcode");
        log.info("deptMap: " + deptMap);


        if (errcode == 0) {
            int id = (int) deptMap.get("id");
            wxDept.setId(id);
            wxDeptMapper.insert(wxDept);
            return true;
        }
        return false;
    }

    /**
     * 更新部门
     *
     * @param wxDept
     * @return
     */
    public boolean updateDept(WxDept wxDept) {
        String accessToken = getAccessToken(WorkWXAPI.ADDRESS_BOOK_SECRET);
        if (accessToken == null) {
            log.error("更新部门：获取Token失败！");
            return false;
        }
        Map<String, Object> deptMap = new HashMap<>();
        deptMap.put("id", wxDept.getId());
        if (wxDept.getName() != null) {
            deptMap.put("name", wxDept.getName());
        }
        if (wxDept.getName_en() != null) {
            deptMap.put("name_en", wxDept.getName_en());
        }
        if (wxDept.getParentid() != null) {
            deptMap.put("parentid", wxDept.getParentid());
        }
        if (wxDept.getPx() != null) {
            deptMap.put("order", wxDept.getPx());
        }

        deptMap = JsonUtil.toMap(HttpClientUtil.post(String.format(WorkWXAPI.UPDATE_DEPT, accessToken), JsonUtil.toJson(deptMap)));
        int errcode = (int) deptMap.get("errcode");
        log.info("deptMap: " + deptMap);
        if (errcode == 0) {
            int id = wxDept.getId();
            wxDept.setId(id);
            wxDeptMapper.updateById(wxDept);
            return true;
        }
        return false;
    }

    /**
     * 删除部门
     *
     * @param id
     * @return
     */
    public boolean deleteDept(int id) {
        String accessToken = getAccessToken(WorkWXAPI.ADDRESS_BOOK_SECRET);
        if (accessToken == null) {
            log.error("删除部门：获取Token失败！");
            return false;
        }
        Map<String, Object> deptMap = new HashMap<>();
        deptMap = JsonUtil.toMap(HttpClientUtil.get(String.format(WorkWXAPI.DELETE_DEPT, accessToken, id)));
        int errcode = (int) deptMap.get("errcode");
        log.info("deptMap: " + deptMap);
        if (errcode == 0) {
            wxDeptMapper.deleteById(id);
            return true;
        }
        return false;
    }

    /**
     * 删除部门及其子部门
     *
     * @param id
     * @return
     */
    public boolean delDepts(int id) {
        String accessToken = getAccessToken(WorkWXAPI.ADDRESS_BOOK_SECRET);
        if (accessToken == null) {
            log.error("删除部门：获取Token失败！");
            return false;
        }
        Map<String, Object> deptMap = new HashMap<>();
        deptMap = JsonUtil.toMap(HttpClientUtil.get(String.format(WorkWXAPI.DELETE_DEPTS, accessToken, id)));
        int errcode = (int) deptMap.get("errcode");
        log.info("deptMap: " + deptMap);
        boolean msg = false;
        if (errcode == 0) {
            List<Map<String, Integer>> list = (List<Map<String, Integer>>) deptMap.get("department_id");
            Stack<Integer> stack = new Stack<>();
            for (Map<String, Integer> map : list) {
                stack.push(map.get("id"));
            }
            while (!stack.isEmpty()) {
                //删除
                msg = deleteDept(stack.pop());
            }
            return msg;
        }
        return msg;
    }

    public boolean createUser(Map<String, Object> map) {
        String accessToken = getAccessToken(WorkWXAPI.ADDRESS_BOOK_SECRET);
        if (accessToken == null) {
            log.error("删除部门：获取Token失败！");
            return false;
        }
        Map<String, Object> deptMap = new HashMap<>();
        deptMap = JsonUtil.toMap(HttpClientUtil.post(String.format(WorkWXAPI.CONTACTS_CREATE, accessToken), JsonUtil.toJson(map)));
        int errcode = (int) deptMap.get("errcode");
        log.info("createUser:" + deptMap);
        if (errcode == 0) {
            return true;
        }
        return false;
    }

}
